import { Controller, Post, UseInterceptors, UploadedFile, HttpException, HttpStatus } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Express } from 'express';
import * as dayjs from 'dayjs';
import * as qiNiu from 'qiniu'
import * as fs from 'node:fs';

const accessKey = '455XY0Tk1W21lXYaYzJ3p1ZGaFSG2oSWR6v35ttn';
const secretKey = 'z3xGjxChdovZ6HfqB9RluKakJYfAiRMCvLMurfbh';
const bucket = 'cyjblog'
const websiteUrl = 'http://qny.bioart.icu/'
const config = new qiNiu.conf.Config();
config.zone = qiNiu.zone.Zone_z2;

@Controller('upload')
export class UploadController {

  @Post('/')
  @UseInterceptors(FileInterceptor('file', {dest:'uploads/'}))
  async upload(@UploadedFile() file: Express.Multer.File) {
    // 获取上传的文件原始名和路径
    const {originalname,path} = file

    // 获取文件类型
    const fileType = originalname.split(".")[1]
    const formattedDateTime = dayjs().format('YYYY-MM-DD-HH:mm:ss:SSS')
    const fileName = dayjs().format('YYYY-MM-DD')

    // 定义鉴权对象mac
    let mac = new qiNiu.auth.digest.Mac(accessKey, secretKey);
    // 上传凭证配置
    let options = {
      scope: bucket,
    };
    // 获取上传凭证uploadToken
    let putPolicy = new qiNiu.rs.PutPolicy(options);
    let uploadToken= putPolicy.uploadToken(mac);
    // 本地文件地址
    let localFile = path;
    // 构造上传器实例
    let formUploader = new qiNiu.form_up.FormUploader(config);
    // 提供上传文件时的额外选项和自定义设置 这里不设置
    let putExtra = new qiNiu.form_up.PutExtra();
    // 上传的文件名设置
    let key= "blog/" + fileName + "/" +formattedDateTime + '.' + fileType ;

    // 文件上传
    const result = await formUploader.putFile(uploadToken, key, localFile, putExtra);

    fs.unlinkSync(path)

    if (result.resp.statusCode === 200) {
      return { url: websiteUrl+key }
    } else {
      throw new HttpException(result.resp,HttpStatus.BAD_REQUEST)
    }
  }
}
